package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.common.util.file.FileUploadUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private RepositoryService repositoryService;
    
    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }

    @Override
    public String uploadFile(MultipartFile file) throws IOException {
        // 检查文件格式
        String extension = FileUploadUtils.getExtension(file);
        if (!"bpmn".equals(extension)) {
            throw new BusinessException("格式不正确，请上传bpmn文件");
        }

        // 上传文件
        String path = FileUploadUtils.upload(SystemConfig.getProfile(), file);
        return path;
    }

    @Override
    @Transactional
    public void deploy(String path, String bpmnType, String info) throws FileNotFoundException {
        // 通过path获取file
        File file = new File(SystemConfig.getProfile(),path);

        // 流程部署
        Deployment deploy = repositoryService.createDeployment().addInputStream(path, new FileInputStream(file)).deploy();

        // 更新bpmnInfo表
        BpmnInfo bpmnInfo = new BpmnInfo();
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploy.getId()).singleResult();

        bpmnInfo.setBpmnType(bpmnType);
        bpmnInfo.setDeploymentId(deploy.getId());
        bpmnInfo.setDeployTime(deploy.getDeploymentTime());
        bpmnInfo.setInfo(info);
        bpmnInfo.setBpmnName(processDefinition.getName());
        bpmnInfo.setActProcessId(processDefinition.getId());
        bpmnInfo.setActProcessKey(processDefinition.getKey());
        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public InputStream readResource(Long deploymentId,String type) {
        InputStream inputStream = null;

        // 获取流程定义对象
        ProcessDefinition processDefinition = repositoryService
                .createProcessDefinitionQuery()
                .deploymentId(deploymentId.toString())
                .singleResult();
        // 通过流程定义对象 获取 bpmn文件名
        String resourceName = processDefinition.getResourceName();

        if ("xml".equals(type)) {
            inputStream = repositoryService.getResourceAsStream(deploymentId.toString(), resourceName);
        }else {
            // 获取配置类ProcessDiagramGenerator 用其API获取流程图的输入流
            ProcessDiagramGenerator diagramGenerator = new DefaultProcessDiagramGenerator();
            // 通过RepositoryService获取bpmnModel
            BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
            inputStream = diagramGenerator.generateDiagram(bpmnModel, Collections.emptyList(), Collections.emptyList(),
                    "宋体", "宋体", "宋体");
        }
        return inputStream;
    }

    @Override
    @Transactional
    public void delete(Long id) {
        // 考虑有无正在执行的流程实例

        // 删除bpmnInfo表信息
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(id);
        bpmnInfoMapper.deleteByPrimaryKey(id);

        // 删除流程定义(删除流程定义前，先从流程定义对象获取 bpmn文件名resourceName)
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(bpmnInfo.getDeploymentId()).singleResult();
        String resourceName = processDefinition.getResourceName();
        repositoryService.deleteDeployment(bpmnInfo.getDeploymentId());

        // 删除服务器流程bpmn文件
        File file = new File(SystemConfig.getProfile(),resourceName);
        if (file.exists()) {
            file.delete();
        }
    }

    @Override
    public List<BpmnInfo> queryByType(String car_package) {
        return bpmnInfoMapper.selectByType(car_package);
    }
}
